package com.ibuu.demos.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ibuu.demos.mapper.PayMapper;
import com.ibuu.demos.pojo.Details;
import com.ibuu.dto.PayRequest;
import com.ibuu.demos.pojo.ShopingCar;
import com.ibuu.demos.service.CategoriesService;
import com.ibuu.demos.service.PayService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class PayServiceImpl extends ServiceImpl<PayMapper, Details> implements PayService {

    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private PayMapper PayMapper;

    @Override
    public void pay(HttpServletRequest request, PayRequest payRequest) {
        //获取当前系统时间
//        Date date = new Date(System.currentTimeMillis());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
//        String time = sdf.format(date);
        long l = System.currentTimeMillis();
        //将时间戳转换为字符串
        String time = String.valueOf(l);

        //去除时间中的点
//        time = time.replace(".", "");
        String timeString = String.valueOf(time);

        //获取购物车
        List<ShopingCar> shopingCar = payRequest.getShopingCar();
        String username = payRequest.getUserInfo().getUsername();
        String email = payRequest.getUserInfo().getEmail();
        Integer a=0;
        for (ShopingCar car : shopingCar) {
            Integer price = car.getPrice();
            Integer num = car.getNum();
            Integer total = price * num;
            a=a+total;
        }



        //添加到订单表
        for (ShopingCar car : shopingCar) {
            Integer price = car.getPrice();
            Integer num = car.getNum();
            Integer total = price * num;
            // 创建一个新的 Details 对象
            Details detail = new Details();

    // 获取购物车商品的 shopid 并转换为字符串
            String s = car.getShopid().toString();
    // 复制购物车商品属性到订单详情对象，忽略 id 属性
            BeanUtils.copyProperties(car, detail, "id");
    // 设置订单详情的 shopid
            detail.setShopid(s);
    // 设置订单 ID
            detail.setId(timeString + username);
    // 设置用户名
            detail.setUsername(username);
    // 设置用户邮箱
            detail.setEmail(email);
    // 设置订单创建时间
            detail.setCreateTime(time);
            detail.setPrice(total);
            detail.setFprice(a);
    // 将订单详情插入数据库
            PayMapper.insert(detail);
            categoriesService.deleteCategories(username);
        }

    }
}